/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.model;


import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.RollbackException;
import org.mybeans.dao.GenericDAO;
import org.mybeans.factory.Transaction;

import scheduler.databean.Lecture;

public class LectureDaoBeanFactoryImpl
    extends GenericDAO<Lecture> 
    implements LectureDao { 
	
    public LectureDaoBeanFactoryImpl(String dbDriver, String dbUrl) {
        this(BeanTable.getSQLInstance(Lecture.class, "lecture", dbDriver, dbUrl));
    }
    
    private LectureDaoBeanFactoryImpl(BeanTable<Lecture> table) {
        super(table, "id");
        getTable().setIdleConnectionCleanup(true);
        setUseAutoIncrementOnCreate(true);
    }
    
    public Lecture create() throws DAOException {
        try {
            return getFactory().create();
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public Lecture create(int courseId, String lectureNumber, String[] day, String[] startTime, int[] duration, String[] classroom, String ins)
        throws DAOException {
        try {
            Transaction.begin();
            Lecture newLecture = create();
            newLecture.setCourseId(courseId);
            newLecture.setLectureNumber(lectureNumber);
            newLecture.setDay(day);
            newLecture.setStartTime(startTime); 
            newLecture.setDuration(duration);  
            newLecture.setClassroom(classroom);
            newLecture.setInstructor(ins);    
            Transaction.commit();
            return newLecture;
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public int countLine(String info) {
    	int count = 1;
    	for (int i = 0; i < info.length(); i++)
    		if (info.charAt(i) == '/')
    			count++;

    	return count;
    }
    
    /*
     * 
	private int		id;
	private int		courseId;
	private String	lectureNumber;
	private String[]	day;
	private String[]	startTime;
	private int[]		duration;
	private String	instructor;
	private String[]	classroom;
     */
    public String parseTime(String time) {
		String timeParsed = time.substring(0, 2) + time.substring(3, 5);
		if (time.charAt(5) == 'P' && ! time.substring(0, 2).equals("12")) {
			timeParsed = (Integer.parseInt(time.substring(0, 2)) + 12) + time.substring(3, 5);
		}
		return timeParsed;
    }
    
    public int calDuration(String startTime, String endTime) {
		int duration = (Integer.parseInt(endTime.substring(0, 2)) - Integer.parseInt(startTime.substring(0, 2))) * 60;
		duration += Integer.parseInt(endTime.substring(2)) - Integer.parseInt(startTime.substring(2));
		duration = (duration / 30 + ((duration % 30 != 0)? 1 : 0)) * 30;
    	return duration;
    }
    
    public int[] nextChunkIndex(String info, int beginningIndex) {
    	int firstNonSpace = beginningIndex;
    	for (int i = beginningIndex; i < info.length(); i++) {
	    	if (info.charAt(i) != ' ') {
	    		firstNonSpace = i;
	    		break;
	    	}
    	}
    	int chunkEnd = info.indexOf(' ', firstNonSpace);
    	if (chunkEnd == -1)
    		chunkEnd = info.length() - 1;
    	return new int[] {firstNonSpace, chunkEnd};
    }
    
    public Lecture create(int courseId, String info) throws DAOException {
        try {
            Transaction.begin();
            Lecture newLecture = create();
            newLecture.setCourseId(courseId);
            
            // "Lec 1 MW 08:30AM 09:20AM IA SIM AU Ijiri"
            // "Lec W 02:30PM 03:20PM MI 355 Marciszyn / W 02:30PM 03:20PM MI 355 Marciszyn"
			int numLine = countLine(info);
			String[] dayArray = new String[numLine];
			String[] startTimeArray = new String[numLine];
			int[] durationArray = new int[numLine];
			String[] classroomArray = new String[numLine];
	    	
			int[] lectureNumber = nextChunkIndex(info, nextChunkIndex(info, 0)[1]);
			
			int nextLine;
            try {
            	Integer.parseInt(info.substring(lectureNumber[0], lectureNumber[1]));
            	newLecture.setLectureNumber(info.substring(lectureNumber[0], lectureNumber[1]));
            	nextLine = nextChunkIndex(info, lectureNumber[1])[0];
            } catch (NumberFormatException ex) {
            	newLecture.setLectureNumber("");
    	        nextLine = lectureNumber[0];
            }
        
			for (int i = 0; i < numLine; i++) {
				int day = info.indexOf(' ', nextLine);
				int startTime = info.indexOf(' ', day + 1);
				int endTime = info.indexOf(' ', startTime + 1);
				int building = info.indexOf(' ', endTime + 1);
				int room = info.indexOf(' ', building + 1);
	
				dayArray[i] = info.substring(nextLine, day);
				startTimeArray[i] = parseTime(info.substring(day + 1, startTime));
				durationArray[i] = calDuration(startTimeArray[i], parseTime(info.substring(startTime + 1, endTime)));
				classroomArray[i] = info.substring(endTime + 1, building) + " " + ((room == -1)? info.substring(building + 1) : info.substring(building + 1, room));
				
				nextLine = info.indexOf('/', nextLine) + 2;
				if (i == 0) {
					newLecture.setInstructor( (numLine == 1)? info.substring(room + 1) : info.substring(room + 1, nextLine - 3));
				}
			}
		
			newLecture.setDay(dayArray);
			newLecture.setStartTime(startTimeArray);
			newLecture.setDuration(durationArray);
			newLecture.setClassroom(classroomArray);
			
	        Transaction.commit();
	        return newLecture;
	    } catch (RollbackException e) {
	        throw new DAOException(e);
	    }
    }
    
    public Lecture lookup(int id) throws DAOException {
        try {
            return getFactory().lookup(id);
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    


	
}
